import { ref } from 'vue'
import type { Ref } from 'vue'
import router from '@/router/index'
export const message = ref('')
export class webSocket {
    url: string;
    callData: string = '';
    ws: any;
    message: Ref<string>
    constructor(url: string) {
        this.url = url
        this.message = ref('1')
    }
    async connect(msg: string) {
        this.ws = new WebSocket(this.url)
        // 建立 web socket 连接成功触发事件
        this.ws.onopen = () => {
            this.send(msg);
        }
        // 接收服务端数据时触发事件; 服务器数据可能是文本，也可能是二进制数据（blob对象或Arraybuffer对象）
        this.ws.onmessage = (e: MessageEvent) => {
            let _this = this
            let fileReader = new FileReader();
            fileReader.readAsText(e.data)
            fileReader.onload = function () {
                _this.callData = this.result!.toString();
                message.value = this.result!.toString();
            }
        }
        this.close()
    }
    // ws.send()给服务器发送信息
    send(data: any) {
        console.log("")
        console.log("↑：" + data)
        this.ws.send(data);
    }
    // 断开 web socket 连接成功触发事件
    close() {
        this.ws.onclose = ((e: MessageEvent) => {
            console.log('MessageEvent: ', ' 断开连接了');
            router.go(0)
        })
    }
}